package com.wfh.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.wfh.bean.BannerBean;
import com.wfh.bean.ProductBean;
import com.wfh.bean.ShopBean;
import com.wfh.bean.TicketsBean;
import com.wfh.database.DataHelper;
import com.wfh.parse.T_Factory;
import com.wfh.util.Util;

import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcelable;
import android.util.Log;

public class CoreService extends Service {
	private DataHelper datahelper;
	private MyBinder myBinder = new MyBinder();

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return myBinder;
	}

	@Override
	public void onCreate() {
		datahelper = new DataHelper(this.getApplicationContext(), "wfh", null,
				1);
		super.onCreate(); 
	}

	public class MyBinder extends Binder {
		public CoreService getService() {
			return CoreService.this;
		}

	}

	@Override
	public boolean onUnbind(Intent intent) {
		if (datahelper != null)
			datahelper.close();
		return super.onUnbind(intent);
	}

	/**
	 * 第一次登陆需要初始化
	 */

	public void initData(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				// Log.i("macaddress",Util.getMacAdd(context));
				// 初始化数据库表
				if (Util.getShare(context, "firstlogin") == null) {
					datahelper.initData();
					// 获取分店
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					commonParams(params);
					String json = Util.getJson("shops", params);
					Log.i("json",json);
					if (json.equals("false")) {
						return;
					}

					// 获取状态信息
					Map<String, String> map = T_Factory.create("T_Shops")
							.pareseJsonObject(json);

					ArrayList<ShopBean> beanlist = (ArrayList<ShopBean>) T_Factory
							.create("T_Shops").pareseJsonArray(json);
					for (ShopBean bean : beanlist) {
						ContentValues values = new ContentValues();
						values.put("shop_id",
								Integer.parseInt(bean.getShop_id()));
						datahelper.insert("versions", null, values);// 插入version默认值
						values.put("shop_name", bean.getShop_name());
						values.put("shop_address", bean.getShop_address());
						values.put("shop_tel", bean.getShop_tel());
						values.put("shop_phone", bean.getShop_phone());
						values.put("shop_person", bean.getShop_person());
						values.put("latitude", bean.getLatitude());
						values.put("longitude", bean.getLongitude());
						values.put("bak", bean.getBak());
						datahelper.insert("shops", null, values);// 插入分店信息
					}

					// 获取默认分店并设置为当前分店
					String def_json = Util.getJson("init", params);
					if (def_json.equals("false"))
						return;
					Map<String, String> def = T_Factory.create("T_Banner")
							.pareseJsonObject(def_json);
					Util.saveShare(CoreService.this, "shop_id",
							def.get("shop_id"));// 当前店铺id
					Util.saveShare(CoreService.this, "shop_name",
							def.get("shop_name"));// 当前店铺名称
					Util.saveShare(CoreService.this, "macaddress",
							Util.getMacAdd(CoreService.this));// mac地址
					String[] position = getPosition(def.get("shop_id"));// 获取经纬度并保存
					Util.saveShare(CoreService.this, "longitude", position[0]);
					Util.saveShare(CoreService.this, "latitude", position[1]);

					// 创建缓存文件夹
					File file = new File(Util.CACHE);
					file.mkdirs();

					// 创建版本控制
					Util.saveShare(context, Util.V_INIT, "1.00");
					
					//店铺数量
					Util.saveShare(context, "shopcounts", beanlist.size()+"");

					Util.saveShare(context, "firstlogin", "true");

				}
				Util.sendbroadcast(context, Util.D_INIT, null);
			}
		}.start();
	}

	/**
	 * 公共验证模块
	 */

	@SuppressWarnings("unused")
	public void commonParams(List<NameValuePair> params) {
		// 添加请求参数
		params.add(new BasicNameValuePair("app_id", Util.getProperty(this,
				"app_id")));
		params.add(new BasicNameValuePair("shop_id", Util.getShare(this,
				"shop_id")));
	}

	/**
	 * 获取shops
	 */

	public void getShops(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				commonParams(params);
				params.add(new BasicNameValuePair("version", Util.getShare(
						CoreService.this, Util.V_INIT)));
				String json = Util.getJson("shops", params);
				Log.i("json", json);
				if (json.equals("false")) {
					return;
				}
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Shops")
						.pareseJsonObject(json);
				if (map.get("ret").equals("0")) {// 版本无更新
					return;
				}
				ArrayList<ShopBean> beanlist = (ArrayList<ShopBean>) T_Factory
						.create("T_Shops").pareseJsonArray(json);

				datahelper.execSQL("delete from shops");
				Cursor versions = null;
				for (ShopBean bean : beanlist) {
					ContentValues values = new ContentValues();
					values.put("shop_id", Integer.parseInt(bean.getShop_id()));
					values.put("shop_name", bean.getShop_name());
					values.put("shop_address", bean.getShop_address());
					values.put("shop_tel", bean.getShop_tel());
					values.put("shop_phone", bean.getShop_phone());
					values.put("shop_phone", bean.getShop_phone());
					values.put("longitude", bean.getLongitude());
					values.put("latitude", bean.getLatitude());
					values.put("bak", bean.getBak());

					datahelper.insert("shops", null, values);// 插入分店信息

					versions = datahelper.rawQuery(
							"select shop_id from versions where shop_id=?",
							new String[] { bean.getShop_id() });
					if (versions.getCount() == 0) {// 如果是新增店，则插入version默认值
						ContentValues insert = new ContentValues();
						insert.put("shop_id",
								Integer.parseInt(bean.getShop_id()));
						datahelper.insert("versions", null, insert);
					}
				}
				//存储店铺数量
				Util.saveShare(context, "shopcounts", beanlist.size()+"");
				if (versions != null)
					versions.close();
				Util.saveShare(CoreService.this, Util.V_INIT,
						map.get("version"));
				getLocalShops(context, intent);
			}
		}.start();
	}

	/**
	 * 获取shops本地数据库
	 * 
	 * @param context
	 * @param intent
	 */

	public void getLocalShops(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				Cursor cursor = datahelper
						.rawQuery("select * from shops", null);
				if (cursor == null || cursor.getCount() == 0) {
					getShops(context, intent);
					cursor.close();
					return;
				}
				// 获取shops列表
				List<ShopBean> list = new ArrayList<ShopBean>();
				while (cursor.moveToNext()) {
					ShopBean bean = new ShopBean();
					bean.setShop_id(cursor.getInt(cursor
							.getColumnIndex("shop_id")) + "");
					bean.setShop_name(cursor.getString(cursor
							.getColumnIndex("shop_name")));
					bean.setShop_address(cursor.getString(cursor
							.getColumnIndex("shop_address")));
					bean.setShop_person(cursor.getString(cursor
							.getColumnIndex("shop_person")));
					bean.setShop_phone(cursor.getString(cursor
							.getColumnIndex("shop_phone")));
					bean.setShop_tel(cursor.getString(cursor
							.getColumnIndex("shop_tel")));
					bean.setLongitude(cursor.getString(cursor
							.getColumnIndex("longitude")));
					bean.setLatitude(cursor.getString(cursor
							.getColumnIndex("latitude")));
					bean.setBak(cursor.getString(cursor.getColumnIndex("bak")));
					list.add(bean);
				}
				cursor.close();
				Bundle bd = new Bundle();
				bd.putParcelableArrayList("shops",
						(ArrayList<? extends Parcelable>) list);
				Util.sendbroadcast(context, Util.D_SHOPS, bd);
				getShops(context, intent);// 检查是否有更新
			}
		}.start();
	}

	/**
	 * 获取banner
	 * 
	 * @param context
	 * @param intent
	 */
	public void getBanner(final Context context, final Intent intent) {
		new Thread() {
			@Override
			public void run() {
				// 获取当前版本
				String version = datahelper.getVersion(
						Util.getShare(context, "shop_id"), "init");

				if (version == null || version.equals(""))
					return;

				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				commonParams(params);
				params.add(new BasicNameValuePair("version", version));

				String json = Util.getJson("init", params);
//				 Log.i("json",json);
				if (json.equals("false")) {
					return;
				}
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Banner")
						.pareseJsonObject(json);
				if (map.get("ret").equals("0")) {// 版本无更新
					return;
				}
				
				//判断版本是否有问题
				try{
				Double.valueOf(map.get("version"));
				}catch(NumberFormatException e){
					e.printStackTrace();
					return;
				}
				
				datahelper.setVersion(Util.getShare(context, "shop_id"),
						"init", map.get("version"));// 如果有对版本进行更新

				// 获取bean
				@SuppressWarnings("unchecked")
				ArrayList<BannerBean> list = (ArrayList<BannerBean>) T_Factory
						.create("T_Banner").pareseJsonArray(json);
				datahelper.execSQL("delete from banners where shop_id="
						+ Util.getShare(context, "shop_id"));
				for (BannerBean bean : list) {
					/* if (cursor.getCount() == 0) { */
					ContentValues values = new ContentValues();
					values.put("banner_id",
							Integer.parseInt(bean.getBanner_id()));
					values.put("shop_id", Integer.parseInt(bean.getShop_id()));
					values.put("img", bean.getImg());
					values.put("url", bean.getUrl());
					values.put("bak", bean.getBak());
					values.put("position", Integer.parseInt(bean.getPosition()));
					values.put("status", Integer.parseInt(bean.getStatus()));
					datahelper.insert("banners", null, values);
					/* } */
				}
				getLocalBanner(context, intent);
			}

		}.start();
	}

	// 获取banners本地数据
	public void getLocalBanner(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				Cursor cursor = datahelper.rawQuery(
						"select * from banners where shop_id="
								+ Util.getShare(context, "shop_id"), null);

				// 获取banner列表
				List<BannerBean> list = new ArrayList<BannerBean>();
				while (cursor.moveToNext()) {
					BannerBean bean = new BannerBean();
					bean.setBanner_id(cursor.getInt(0) + "");
					// Log.i("banner_id", cursor.getInt(0) + "");
					bean.setShop_id(cursor.getInt(1) + "");
					bean.setImg(cursor.getString(2) + "");
					bean.setUrl(cursor.getString(3) + "");
					bean.setBak(cursor.getString(4) + "");
					bean.setPosition(cursor.getInt(5) + "");
					bean.setStatus(cursor.getInt(6) + "");
					list.add(bean);
				}
				cursor.close();
				Bundle bd = new Bundle();
				bd.putParcelableArrayList("banners",
						(ArrayList<? extends Parcelable>) list);
				Util.sendbroadcast(context, Util.D_HOME, bd);
				getBanner(context, intent);// 检查是否有更新
			}
		}.start();
	}

	/**
	 * 获取限时抢购、本周特价、热销排行、新品推荐
	 * 
	 * @param action
	 * @param context
	 * @param intent
	 */

	public void getProduct(final String action, final Context context,
			final Intent intent) {
		new Thread() {
			@Override
			public void run() {
				// 映射关系
				Map<String, String> atob = new HashMap<String, String>();
				atob.put("weeks", "is_week");
				atob.put("hots", "is_hot");
				atob.put("bests", "is_best");
				atob.put("promotions", "is_promotion");

				// 获取当前版本
				String version = datahelper.getVersion(
						Util.getShare(context, "shop_id"), action);

				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				commonParams(params);
				params.add(new BasicNameValuePair("version", version));

				String json = Util.getJson(action, params);
				 Log.i("json", json);
				if (json.equals("false")) {
					return;
				}
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Product")
						.pareseJsonObject(json);
				if (map.get("ret").equals("0")) {// 版本无更新
					return;
				}
				
				//判断版本是否有问题
				try{
				Double.valueOf(map.get("version"));
				}catch(NumberFormatException e){
					e.printStackTrace();
					return;
				}
				
				// 获取bean
				@SuppressWarnings("unchecked")
				ArrayList<ProductBean> list = (ArrayList<ProductBean>) T_Factory
						.create("T_Product").pareseJsonArray(json);

				datahelper.execSQL("delete from products where shop_id="
						+ Util.getShare(context, "shop_id") + " and "
						+ atob.get(action) + "=1");
				for (ProductBean bean : list) {
					/* if (cursor.getCount() == 0) { */
					ContentValues values = new ContentValues();
					values.put("product_id",
							Integer.parseInt(bean.getProduct_id()));
					values.put("shop_id", Integer.parseInt(bean.getShop_id()));
					values.put("product_name", bean.getProduct_name());
					values.put("product_desc", bean.getProduct_desc());
					values.put("product_img", bean.getProduct_img());
					values.put("product_price", bean.getProduct_price());
					values.put("product_price_oem", bean.getProduct_price_oem());
					values.put("position", Integer.parseInt(bean.getPosition()));
					values.put("is_week", Integer.parseInt(bean.getIs_week()));
					values.put("is_hot", Integer.parseInt(bean.getIs_hot()));
					values.put("is_best", Integer.parseInt(bean.getIs_best()));
					values.put("is_promotion",
							Integer.parseInt(bean.getIs_promotion()));
					values.put("promotion_end_time",
							bean.getPromotion_end_time());
					datahelper.insert("products", null, values);
				}

				datahelper.setVersion(Util.getShare(context, "shop_id"),
						action, map.get("version"));// 如果有对版本进行更新

				getLocalProducts(action, context, intent);
			}

		}.start();
	}

	// 获取products本地数据
	public void getLocalProducts(final String action, final Context context,
			final Intent intent) {

		new Thread() {
			public void run() {
				// 映射关系
				Map<String, String> atob = new HashMap<String, String>();
				atob.put("weeks", "is_week");
				atob.put("hots", "is_hot");
				atob.put("bests", "is_best");
				atob.put("promotions", "is_promotion");

				Cursor cursor = datahelper.rawQuery(
						"select * from products where shop_id="
								+ Util.getShare(context, "shop_id") + " and "
								+ atob.get(action) + "=1", null);
				// 获取banner列表
				List<ProductBean> list = new ArrayList<ProductBean>();
				while (cursor.moveToNext()) {
					ProductBean bean = new ProductBean();
					bean.setProduct_id(cursor.getInt(0) + "");
					bean.setShop_id(cursor.getInt(1) + "");
					bean.setProduct_name(cursor.getString(2));
					bean.setProduct_desc(cursor.getString(3));
					bean.setProduct_img(cursor.getString(4));
					bean.setProduct_price(cursor.getString(5));
					bean.setProduct_price_oem(cursor.getString(6));
					bean.setPosition(cursor.getInt(7) + "");
					bean.setIs_week(cursor.getInt(8) + "");
					bean.setIs_hot(cursor.getInt(9) + "");
					bean.setIs_best(cursor.getInt(10) + "");
					bean.setIs_best(cursor.getInt(11) + "");
					bean.setPromotion_end_time(cursor.getString(12));
					list.add(bean);
				}
				cursor.close();
				Bundle bd = new Bundle();
				bd.putParcelableArrayList("products",
						(ArrayList<? extends Parcelable>) list);
				Util.sendbroadcast(context, Util.D_PRODUCT, bd);
				getProduct(action, context, intent);// 检查是否有更新
			}
		}.start();
	}

	/**
	 * 获取点菜列表
	 * 
	 * @param action
	 * @param context
	 * @param intent
	 */

	public void getOrder(final Context context, final Intent intent) {
		new Thread() {
			@Override
			public void run() {
				// 获取当前版本
				String version = datahelper.getVersion(
						Util.getShare(context, "shop_id"), "products");

				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				commonParams(params);
				params.add(new BasicNameValuePair("version", version));

				String json = Util.getJson("products", params);
				// Log.i("json", json);
				if (json.equals("false")) {
					return;
				}
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Product")
						.pareseJsonObject(json);
				if (map.get("ret").equals("0")) {// 版本无更新
					return;
				}
				datahelper.setVersion(Util.getShare(context, "shop_id"),
						"products", map.get("version"));// 如果有对版本进行更新

				// 获取bean
				@SuppressWarnings("unchecked")
				ArrayList<ProductBean> list = (ArrayList<ProductBean>) T_Factory
						.create("T_Product").pareseJsonArray(json);

				datahelper.execSQL("delete from products where shop_id="
						+ Util.getShare(context, "shop_id"));

				for (ProductBean bean : list) {
					/* if (cursor.getCount() == 0) { */
					ContentValues values = new ContentValues();
					values.put("product_id",
							Integer.parseInt(bean.getProduct_id()));
					values.put("shop_id", Integer.parseInt(bean.getShop_id()));
					values.put("product_name", bean.getProduct_name());
					values.put("product_desc", bean.getProduct_desc());
					values.put("product_img", bean.getProduct_img());
					values.put("product_price", bean.getProduct_price());
					values.put("product_price_oem", bean.getProduct_price_oem());
					values.put("position", Integer.parseInt(bean.getPosition()));
					values.put("is_week", Integer.parseInt(bean.getIs_week()));
					values.put("is_hot", Integer.parseInt(bean.getIs_hot()));
					values.put("is_best", Integer.parseInt(bean.getIs_best()));
					values.put("is_promotion",
							Integer.parseInt(bean.getIs_promotion()));
					values.put("promotion_end_time",
							bean.getPromotion_end_time());
					datahelper.insert("products", null, values);
				}
				Intent intent = new Intent();
				intent.putExtra("order", "product_id");
				intent.putExtra("type", "desc");
				getLocalOrder(context, intent);
			}

		}.start();
	}

	// 获取本地点菜列表
	public void getLocalOrder(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				// 查询条件
				String order = " order by " + intent.getStringExtra("order")
						+ " " + intent.getStringExtra("type");

				// 映射关系
				Cursor cursor = datahelper.rawQuery(
						"select * from products where shop_id="
								+ Util.getShare(context, "shop_id") + order,
						null);
				/*
				 * // Log.i("数量",cursor.getCount()+""); if (cursor.getCount() ==
				 * 0){ getOrder(context, intent); return; }
				 */
				// 获取banner列表
				List<ProductBean> list = new ArrayList<ProductBean>();
				while (cursor.moveToNext()) {
					ProductBean bean = new ProductBean();
					bean.setProduct_id(cursor.getInt(0) + "");
					bean.setShop_id(cursor.getInt(1) + "");
					bean.setProduct_name(cursor.getString(2));
					bean.setProduct_desc(cursor.getString(3));
					bean.setProduct_img(cursor.getString(4));
					bean.setProduct_price(cursor.getString(5));
					bean.setProduct_price_oem(cursor.getString(6));
					bean.setPosition(cursor.getInt(7) + "");
					bean.setIs_week(cursor.getInt(8) + "");
					bean.setIs_hot(cursor.getInt(9) + "");
					bean.setIs_best(cursor.getInt(10) + "");
					bean.setIs_best(cursor.getInt(11) + "");
					bean.setPromotion_end_time(cursor.getString(12));
					list.add(bean);
				}
				cursor.close();
				Bundle bd = new Bundle();
				bd.putParcelableArrayList("products",
						(ArrayList<? extends Parcelable>) list);
				Util.sendbroadcast(context, Util.D_ORDER, bd);
				getOrder(context, intent);// 检查是否有更新
			}
		}.start();
	}

	/**
	 * getphonelist
	 * 
	 * @param context
	 * @param intent
	 */
	public void getPhoneList(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				ArrayList<String> phone = new ArrayList<String>();
				Cursor cursor = datahelper
						.rawQuery(
								"select shop_tel,shop_phone from shops where shop_id=?",
								new String[] { Util.getShare(CoreService.this,
										"shop_id") });
				while (cursor.moveToNext()) {
					phone.add(cursor.getString(0));
					phone.add(cursor.getString(1));
				}
				cursor.close();
				Bundle bd = new Bundle();
				bd.putStringArrayList("phone", phone);
				Util.sendbroadcast(context, Util.D_PHONE, bd);
			}
		}.start();
	}

	/**
	 * 获取代金券列表
	 * 
	 * @param action
	 * @param context
	 * @param intent
	 */

	public void getTickets(final Context context, final Intent intent) {
		new Thread() {
			@Override
			public void run() {

				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				commonParams(params);
				params.add(new BasicNameValuePair("version", "1.00")); // 实时获取,不记录版本号

				String json = Util.getJson("quans", params);
				// Log.i("json", json);
				if (json.equals("false")) {
					return;
				}
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Tickets")
						.pareseJsonObject(json);
				if (map.get("ret").equals("0")) {// 版本无更新
					return;
				}

				// 获取bean
				@SuppressWarnings("unchecked")
				ArrayList<ProductBean> list = (ArrayList<ProductBean>) T_Factory
						.create("T_Tickets").pareseJsonArray(json);
				Bundle bd = new Bundle();
				bd.putParcelableArrayList("tickets", list);
				Util.sendbroadcast(context, Util.D_TICKETS, bd);
			}

		}.start();
	}

	/**
	 * 获取我的优惠券列表
	 * 
	 * @param context
	 * @param intent
	 */
	public void getMyLocalTickets(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				String status = null;
				Cursor cursor = null;
				ArrayList<TicketsBean> list = new ArrayList<TicketsBean>();

				if (intent != null)
					status = intent.getStringExtra("status");
				if (status != null) {
					if (status.equals("2")) {
						cursor = datahelper
								.rawQuery(
										"select * from tickets where shop_id=? and exp_date<?",
										new String[] {
												Util.getShare(CoreService.this,
														"shop_id"),
												Util.getTime("yyyy-MM-dd") });
					} else {
						cursor = datahelper
								.rawQuery(
										"select * from tickets where shop_id=? and status=? and exp_date>?",
										new String[] {
												Util.getShare(CoreService.this,
														"shop_id"), status,
												Util.getTime("yyyy-MM-dd") });
					}
				} else {
					cursor = datahelper.rawQuery(
							"select * from tickets where shop_id=?",
							new String[] { Util.getShare(CoreService.this,
									"shop_id") });
				}

				// 查看是否有自己的优惠券
				Cursor count = datahelper.rawQuery(
						"select * from tickets where shop_id=?",
						new String[] { Util.getShare(CoreService.this,
								"shop_id") });
				if (count == null || count.getCount() == 0) {
					Bundle bd = new Bundle();
					bd.putBoolean("isnull", true);
					Util.sendbroadcast(context, Util.D_MYTICKETS, bd);
					count.close();
					getMyTickets(context, intent, status);
					return;
				}

				while (cursor.moveToNext()) {
					TicketsBean bean = new TicketsBean();
					bean.setJuan_id(cursor.getInt(cursor
							.getColumnIndex("juan_id")) + "");
					bean.setCode(cursor.getString(cursor.getColumnIndex("code"))
							+ "");
					bean.setExp_date(cursor.getString(cursor
							.getColumnIndex("exp_date")) + "");
					bean.setJuan_name(cursor.getString(cursor
							.getColumnIndex("juan_name")) + "");
					bean.setReal_money(cursor.getString(cursor
							.getColumnIndex("real_money")) + "");
					bean.setReduce_money(cursor.getString(cursor
							.getColumnIndex("reduce_money")) + "");
					bean.setStatus(cursor.getInt(cursor
							.getColumnIndex("status")) + "");
					list.add(bean);
				}
				cursor.close();
				Bundle bd = new Bundle();
				bd.putParcelableArrayList("mytickets", list);
				bd.putBoolean("isnull", false);
				Util.sendbroadcast(context, Util.D_MYTICKETS, bd);
				if (status == null)
					getMyTickets(context, intent, status);
			}
		}.start();
	}

	/**
	 * 获取我的优惠券列表
	 * 
	 * @param context
	 * @param intent
	 */
	public void getMyTickets(final Context context, final Intent intent,
			final String status) {
		new Thread() {
			public void run() {
				if (status != null && status.equals("2")) {
					Bundle bd = new Bundle();
					bd.putParcelableArrayList("mytickets", null);
					bd.putBoolean("isnull", false);
					Util.sendbroadcast(context, Util.D_MYTICKETS, bd);
					return;
				}
				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				commonParams(params);
				// 发送mac地址或者账号信息
				params.add(new BasicNameValuePair("mac", Util.getShare(
						CoreService.this, "macaddress")));
				if (status != null)
					params.add(new BasicNameValuePair("status", status));
				String json = Util.getJson("my_quans", params);
//				Log.i("json", json);
				if (json.equals("false")) {
					return;
				}
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Tickets")
						.pareseJsonObject(json);
				if (map.get("ret").equals("0") || map.get("ret").equals("100")
						|| map.get("ret").equals("201")) {// 均不更新
					return;
				}

				ArrayList<TicketsBean> list = (ArrayList<TicketsBean>) T_Factory
						.create("T_Tickets").pareseJsonArray(json);
				if (list.size() == 0 || list == null)
					return;
				String sql;
				if (status != null) {
					sql = "delete from tickets where shop_id="
							+ Util.getShare(CoreService.this, "shop_id")
							+ " and status=" + status;
				} else {
					sql = "delete from tickets where shop_id="
							+ Util.getShare(CoreService.this, "shop_id");
				}
				datahelper.execSQL(sql);
				for (TicketsBean bean : list) {
					ContentValues values = new ContentValues();
					values.put("juan_id", bean.getJuan_id());
					values.put("code", bean.getCode());
					values.put("shop_id",
							Util.getShare(CoreService.this, "shop_id"));
					values.put("exp_date", bean.getExp_date());
					values.put("juan_name", bean.getJuan_name());
					values.put("real_money", bean.getReal_money());
					values.put("reduce_money", bean.getReduce_money());
					values.put("status", bean.getStatus());
					datahelper.insert("tickets", null, values);
				}

				Bundle bd = new Bundle();
				bd.putParcelableArrayList("mytickets", list);
				bd.putBoolean("isnull", false);
				Util.sendbroadcast(context, Util.D_MYTICKETS, bd);
			}
		}.start();
	}

	/**
	 * 领取优惠券
	 * 
	 * @param context
	 * @param intent
	 */

	public void qiangTickets(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				String juan_id = intent.getStringExtra("id");

				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				commonParams(params);
				params.add(new BasicNameValuePair("juan_id", juan_id));
				// 发送mac地址如果绑定用户则发送用户
				if (Util.getShare(context, "user") == null || Util.getShare(context, "user").equals("")) {
					params.add(new BasicNameValuePair("mac", Util.getShare(
							CoreService.this, "macaddress")));
				}else{
					params.add(new BasicNameValuePair("account", Util.getShare(
							CoreService.this, "user")));
				}
				/*Log.i("account",Util.getShare(
						CoreService.this, "user"));*/
				String json = Util.getJson("get_quan", params);
//				Log.i("json", json);
				if (json.equals("false")) {
					return;
				}
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_QTickets")
						.pareseJsonObject(json);

				int ret = Integer.parseInt(map.get("ret"));
				Bundle bd = new Bundle();
				bd.putInt("ret", ret);
				switch (ret) {
				case 201:
					bd.putString("status", "账号不存在");
					break;
				case 102:
					bd.putString("status", "已经领过5次");
					break;
				case 101:
					bd.putString("status", "已经领过1次");
					break;
				case 103:
					bd.putString("status", "券已经过期");
					break;
				case 1:
					TicketsBean bean = (TicketsBean) T_Factory.create("T_QTickets")
					.pareseJsonBean(json);
					ContentValues values = new ContentValues();
					values.put("juan_id", Integer.parseInt(juan_id));
					values.put("code", bean.getCode());
					values.put("shop_id",
							Util.getShare(CoreService.this, "shop_id"));
					values.put("exp_date", bean.getExp_date());
					values.put("juan_name", bean.getJuan_name());
					values.put("real_money", bean.getReal_money());
					values.put("reduce_money", bean.getReduce_money());
					values.put("status", 0);
					datahelper.insert("tickets", null, values);
					bd.putString("status", "领取成功");
					break;
				default:
					break;
				}

				bd.putInt("ret", ret);
				Util.sendbroadcast(CoreService.this, Util.D_QTICKETS, bd);
			}
		}.start();
	}

	// 获取经纬度
	public String[] getPosition(String shop_id) {
		String[] position = new String[2];
		Cursor cursor = datahelper.rawQuery(
				"select * from shops where shop_id=?",
				new String[] { shop_id });
		cursor.moveToNext();
		position[0] = cursor.getString(cursor.getColumnIndex("longitude"));
		position[1] = cursor.getString(cursor.getColumnIndex("latitude"));
		cursor.close();
		return position;

	}

	// 获取企业介绍
	public void getInfo(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				Cursor cursor = datahelper.rawQuery(
						"select * from shops where shop_id=?",
						new String[] { Util.getShare(CoreService.this,
								"shop_id") });
				if (cursor == null && cursor.getCount() == 0)
					return;
				cursor.moveToNext();
				Bundle bd = new Bundle();
				bd.putString("info",
						cursor.getString(cursor.getColumnIndex("bak")));
				bd.putInt("action", 1);
				cursor.close();
				Util.sendbroadcast(CoreService.this, Util.D_SETTING, bd);

			}
		}.start();

	}

	// 获取最新版本
	public void getNewVersion(final Context context, final Intent intent) {
		new Thread() {
			// Bundle bd = intent.getExtras();
			String json;

			public void run() {
				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				commonParams(params);
				json = Util.getJson("app_version", params);
				if (json.equals("false")) {
					Util.sendbroadcast(context, Util.D_SETTING, null);
					return;
				}
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Update")
						.pareseJsonObject(json);

				Bundle bd = new Bundle();
				bd.putInt("action", 2);
				if (map.get("ret").equals("0")) {
					bd.putString("ret", map.get("ret"));
					Util.sendbroadcast(context, Util.D_SETTING, bd);
					return;
				}
				bd.putString("ret", map.get("ret"));
				bd.putString("version_code", map.get("version_code"));
				bd.putString("file_url", map.get("file_url"));
				bd.putString("bak", map.get("bak"));
				Util.sendbroadcast(context, Util.D_SETTING, bd);

			}
		}.start();
	}

	// 下载apk包
	public void getApk(final Context context, final Intent intent) {
		new Thread() {
			Bundle bd = intent.getExtras();
			String file_url = bd.getString("file_url");

			public void run() {
				try {
					// 获取文件输入流
					URL url = new URL(file_url);
					URLConnection conn = url.openConnection();
					InputStream is = conn.getInputStream();
					int total = conn.getContentLength();
					int current = 0;
					int count = 0;
					byte[] buffer = new byte[1024];

					// 创建缓存文件并创建输出流把网络数据写入输出流
					File file = new File(Util.getSdPath() + "/tempwfh.apk");
					if (!file.exists())
						file.createNewFile();

					FileOutputStream fos = new FileOutputStream(file);
					Bundle bd = new Bundle();
					while ((count = is.read(buffer, 0, buffer.length)) != -1) {
						fos.write(buffer, 0, count);
						current += count;
						bd.putString("percent", ((float) current / total * 100)
								+ "%");
						bd.putInt("action", 3);
						Util.sendbroadcast(context, Util.D_SETTING, bd);
					}

					is.close();
					fos.flush();
					fos.close();

					// 下载完毕进行安装
					Intent intent = new Intent();
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setAction(android.content.Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.fromFile(file),
							"application/vnd.android.package-archive");
					startActivity(intent);

				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}.start();
	}

	/**
	 * 注册账号请求
	 * 
	 * @param context
	 * @param intent
	 */

	public void regist(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				Bundle bd = intent.getExtras();
				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				// commonParams(params);
				// 发送请求注册
				params.add(new BasicNameValuePair("account", bd
						.getString("user")));
				params.add(new BasicNameValuePair("passwd", bd
						.getString("pass")));
				String json = Util.getAJson("Account", "register", params);
				Log.i("json", json);
				if (json.equals("false")) {
					return;
				}

				Bundle bd1 = new Bundle();
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Regist")
						.pareseJsonObject(json);

				bd1.putString("ret", map.get("ret"));
				Util.sendbroadcast(context, Util.D_REGIST, bd1);
			}
		}.start();

	}

	/**
	 * 登陆
	 * 
	 * @param context
	 * @param intent
	 */

	public void login(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				Bundle bd = intent.getExtras();
				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				// commonParams(params);
				// 发送请求注册
				params.add(new BasicNameValuePair("account", bd
						.getString("user")));
				params.add(new BasicNameValuePair("passwd", bd
						.getString("pass")));
				Log.i("xxx", bd.getString("user") + bd.getString("pass"));
				String json = Util.getAJson("Account", "login", params);
				if (json.equals("false")) {
					return;
				}

				Bundle bd1 = new Bundle();
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Regist")
						.pareseJsonObject(json);

				bd1.putString("ret", map.get("ret"));
				bd1.putInt("action", 1);
				Util.sendbroadcast(context, Util.D_LOGININ, bd1);
			}
		}.start();

	}

	/**
	 * 绑定账号
	 * 
	 * @param context
	 * @param intent
	 */

	public void bindAccount(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				commonParams(params);
				// 发送请求注册
				params.add(new BasicNameValuePair("account", Util.getShare(
						context, "user")));
				params.add(new BasicNameValuePair("passwd", Util.getShare(
						context, "pass")));
				params.add(new BasicNameValuePair("mac", Util.getShare(context,
						"mac")));
				String json = Util.getAJson("Account", "bind", params);
				if (json.equals("false")) {
					return;
				}

				Bundle bd1 = new Bundle();
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Regist")
						.pareseJsonObject(json);

				bd1.putString("ret", map.get("ret"));
				bd1.putInt("action", 2);
				Util.sendbroadcast(context, Util.D_LOGININ, bd1);
			}
		}.start();

	}

	/**
	 * 获取积分
	 * 
	 * @param context
	 * @param intent
	 */

	public void getScore(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				// Bundle bd = intent.getExtras();
				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				// commonParams(params);
				// 发送请求注册
				params.add(new BasicNameValuePair("account", Util.getShare(
						context, "user")));
				String json = Util.getAJson("Account", "my_score", params);
				// Log.i("json", json);
				if (json.equals("false")) {
					Util.sendbroadcast(context, Util.D_SETTING, null);
					return;
				}

				Bundle bd1 = new Bundle();
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Score")
						.pareseJsonObject(json);
				bd1.putInt("action", 4);
				bd1.putString("ret", map.get("ret"));
				if (map.containsKey("score"))
					bd1.putString("score", map.get("score"));
				Util.sendbroadcast(context, Util.D_SETTING, bd1);
			}
		}.start();

	}

	/**
	 * 获取积分
	 * 
	 * @param context
	 * @param intent
	 */

	public void findPassword(final Context context, final Intent intent) {
		new Thread() {
			public void run() {
				Bundle bd = intent.getExtras();
				// 请求参数列表
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("account", bd
						.getString("account")));
				String json = Util.getAJson("Account", "find_pwd", params);
				Log.i("json", json);
				if (json.equals("false")) {
					Util.sendbroadcast(context, Util.D_FINDPASSWORD, null);
					return;
				}

				Bundle bd1 = new Bundle();
				// 获取状态信息
				Map<String, String> map = T_Factory.create("T_Findpassword")
						.pareseJsonObject(json);
				bd1.putString("ret", map.get("ret"));
				Util.sendbroadcast(context, Util.D_FINDPASSWORD, bd1);
			}
		}.start();

	}

	@Override
	public void onDestroy() {
		if (datahelper != null)
			datahelper.close();
		super.onDestroy();

	}

}
